/*
 * @Author: Yuluo 568055454@qq.com
 * @Date: 2023年05月27日 01:15:40
 * @LastEditors: Yuluo 568055454@qq.com
 * @LastEditTime: 2023年06月21日 00:52:03
 * @FilePath: \Mood-Blog-System\back\app.js
 * @Description:  项目入口文件，启动服务器，加载中间件，路由，公共资源等
 * Copyright (c) 2023 by Yuluo, All Rights Reserved. 
 */
const dotenv = require('dotenv');
dotenv.config();

const Koa = require('koa');
const app = new Koa({ proxy: true });

const db = require('./db');

const router = require('./routes');
const middlewares = require('./middlewares');
const cors = require('@koa/cors')

const { server, staticPath } = require('./config');

// 启动数据库
db.install(app);

// 中间件：跨域
app.use(cors());

// 中间件：解析请求体
app.use(require('koa-bodyparser')());

// 中间件：记录访问日志
middlewares.install(app, 'before');

// 路由
app.use(router.routes());
app.use(router.allowedMethods());

// 中间件：记录响应日志
middlewares.install(app, 'after');

// 公共资源
app.use(require('koa-static')(__dirname + '/' + staticPath));

// 启动服务器
app.listen(server.port, () => {
    console.log(`Server is running: http://localhost:${server.port}`);
});
// (async () => {
//     const { sendEmail } = require('./util/mailer');
//     const { generateRandomCode } = require('./util/core');
//     const { email } = require('./config');
//     const expireTime = Date.now() + email.expireTime;
//     const to = '1511207059@qq.com';
//     const from = '568055454@qq.com';
//     const authCode = email.authCode;
//     const sendCode = await generateRandomCode(6);
//     sendEmail(to, from, authCode, sendCode).then(res => {
//         console.log('发送成功');
//         console.log(app.context.emailCode);
//         app.context.emailCode = sendCode;
//     })
// })()
module.exports = app;